<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item>
              <el-input v-model="query.title" placeholder="输入信息标题" clearable> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-select v-model="query.status" placeholder="信息状态" clearable>
                <el-option v-for="(item, index) in infoStateOptions" :key="index" :label="item.fullName" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-select v-model="query.typeId" placeholder="信息类型" clearable @focus="getAssoInfoTypeListData()">
                <el-option v-for="(item, index) in typeIdOptions" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item>
              <el-date-picker v-model="query.approveTime" value-format="timestamp" format="yyyy-MM-dd"
                start-placeholder="发布开始日期" end-placeholder="发布结束日期" type="daterange" />
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item>
              <userSelect v-model="query.lastModifyUserId" placeholder="发布人员" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div>
            <el-button v-has="'btn_add'" type="primary" @click="addOrUpdateHandle()">新增信息</el-button>
            <!-- <el-dropdown placement="bottom" @command="handleBatchUnApprove">
              <el-button plain @click="handleBatchApprove()">
                批量通过<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="handleBatchUnApprove">批量驳回</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
          </div>
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table v-loading="listLoading" :data="list" @sort-change='sortChange' :customColumn="true">
          <el-table-column prop="title" label="信息标题" align="left" />
          <el-table-column prop="flowState" label="信息状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.flowState==1">待审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.flowState==2">已发布</el-tag>
              <el-tag type="danger" v-else-if="scope.row.flowState==3">已驳回</el-tag>
              <!-- <el-tag type="info" v-else-if="scope.row.flowState==4">流程撤回</el-tag> -->
              <!-- <el-tag type="info" v-else-if="scope.row.flowState==5">审核终止</el-tag> -->
              <el-tag type="warning" v-else-if="scope.row.flowState==0">草稿</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="信息类型" prop="typeId" algin="left">
            <template slot-scope="scope">
              {{ scope.row.typeId | dynamicText(typeIdOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="approveTime" label="发布时间" align="left" />
          <el-table-column prop="lastModifyUserName" label="发布人员" align="left" />
          <el-table-column label="操作" fixed="right" width="150">
            <template slot-scope="scope">
              <el-button v-has="'btn_edit'" type="text" @click="addOrUpdateHandle(scope.row.id)" v-if="[3,0].indexOf(scope.row.flowState)>-1">编辑</el-button>
              <el-button v-has="'btn_detail'" size="mini" type="text" v-if="[1,2].indexOf(scope.row.flowState)>-1"
                @click="addOrUpdateHandle(scope.row.id,scope.row.flowState)">详情</el-button>
              <el-button v-has="'btn_cancelRelease'" type="text" v-if="[2].indexOf(scope.row.flowState)>-1" @click="cancelPublish(scope.row.id)">取消发布</el-button>
              <el-button v-has="'btn_remove'" type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </JNPF-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
          @pagination="initData" />
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="批量审核通过进度"
      :visible.sync="batchApproveVisible"
      width="400px"
    >
      <div class="askDialog">
        <div class="progressBox">
          <el-progress
            class="progress"
            :text-inside="true"
            :stroke-width="24"
            :percentage="parseInt(progressNumApprove)"
          />
          <el-card v-if="isCardApprove">
            <div>
              <div class="successes">成功数量：{{ successesNumApprove }}</div>
              <div class="failures">失败数量：{{ failuresNumApprove }}</div>
              <div class="information">
                <div v-for="(item, index) in informationApprove" :key="index">
                  <div class="informationText">{{ item }}</div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        <div class="progressIcon" @click="isCardApprove = !isCardApprove">
          <i class="el-icon-yzzxiangqing" />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          @click="batchApproveVisible = false"
        >取消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="批量审核驳回进度"
      :visible.sync="batchUnApproveVisible"
      width="400px"
    >
      <div class="askDialog">
        <div class="progressBox">
          <el-progress
            class="progress"
            :text-inside="true"
            :stroke-width="24"
            :percentage="parseInt(progressNumUnApprove)"
          />
          <el-card v-if="isCardUnApprove">
            <div>
              <div class="successes">成功数量：{{ successesNumUnApprove }}</div>
              <div class="failures">失败数量：{{ failuresNumUnApprove }}</div>
              <div class="information">
                <div v-for="(item, index) in informationUnApprove" :key="index">
                  <div class="informationText">{{ item }}</div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        <div class="progressIcon" @click="isCardUnApprove = !isCardUnApprove">
          <i class="el-icon-yzzxiangqing" />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          @click="batchUnApproveVisible = false"
        >取消</el-button>
      </span>
    </el-dialog>
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" :displayReturn="false" />
  </div>
</template>

<script>
  import request from '@/utils/request'
  import { getAssoInfoTypeList } from '@/api/asso/info/category'
  import FlowBox from '@/views/workFlow/components/FlowBox'

  import columnList from './columnList'

  export default {
    components: {
      FlowBox
    },
    data() {
      return {
        expandObj: {},
        columnOptions: [],
        mergeList: [],
        columnList,

        query: {
          title: undefined,
          typeId: undefined,
        },
        treeProps: {
          children: 'children',
          label: 'fullName',
          value: 'id'
        },
        list: [],
        listLoading: true,
        multipleSelection: [],
        total: 0,
        listQuery: {
          superQueryJson: '',
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "",
        },
        flowVisible: false,
        typeIdOptions: [],
        infoStateOptions: [{
          "fullName": "待审核",
          "id": 1
        }, {
          "fullName": "已发布",
          "id": 2
        }, {
          "fullName": "已驳回",
          "id": 3
        }, {
          "fullName": "草稿",
          "id": 0
        }],
        typeIdProps: {
          "label": "fullName",
          "value": "id"
        },
        batchApproveVisible: false,
        batchUnApproveVisible: false,
        successesNumApprove: 0, // 成功数
        failuresNumApprove: 0, // 失败数
        successesNumUnApprove: 0, // 成功数
        failuresNumUnApprove: 0, // 失败数
        information: [],
        isCardApprove: false,
        isCardUnApprove: false,
        progressNumApprove: 0,
        progressNumUnApprove: 0,
      }
    },
    created() {
      this.initData()
      this.getAssoInfoTypeListData()
    },
    methods: {
      getAssoInfoTypeListData() {
        let _query = {
          superQueryJson: '',
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: ""
        };
        request({
          url: `/api/zgyf/AssoInfoType/Selector`,
          method: 'get'
        }).then(res => {
          res.data.list.forEach(item => {
            item.fullName = item.name
          })
          this.typeIdOptions = JSON.parse(JSON.stringify(res.data.list))
        })
      },
      sortChange({
        column,
        prop,
        order
      }) {
        this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
        this.listQuery.sidx = !order ? '' : prop
        this.initData()
      },
      initData() {
        this.listLoading = true;
        let _query = {
          ...this.listQuery,
          ...this.query,
          keyword: this.keyword,
          dataType: 0
        };
        request({
          url: `/api/zgyf/AssoInfo/getList`,
          method: 'post',
          data: _query
        }).then(res => {
          this.list = JSON.parse(JSON.stringify(res.data.list))
          this.total = res.data.pagination.total
          this.listLoading = false
        })
      },
      handleDel(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          type: 'warning'
        }).then(() => {
          request({
            url: `/api/zgyf/AssoInfo/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            });
          })
        }).catch(() => {});
      },
      cancelPublish(id) {
        this.$confirm('是否确认取消发布?', '提示', {
          type: 'warning'
        }).then(() => {
          request({
            url: `/api/zgyf/AssoInfo/CancelPublish/${id}`,
            method: 'put'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            });
          })
        }).catch(() => {});
      },
      addOrUpdateHandle(id, flowState) {
        let data = {
          id: id || '',
          enCode: 'infoList',
          flowId: '366183874633400645',
          formType: 1,
          opType: flowState ? 0 : '-1',
          status: flowState
        }
        this.flowVisible = true
        this.$nextTick(() => {
          this.$refs.FlowBox.init(data)
        })
      },
      search() {
        this.listQuery.currentPage = 1
        this.listQuery.pageSize = 20
        this.listQuery.sort = "desc"
        this.listQuery.sidx = ""
        this.initData()
      },
      colseFlow(isrRefresh) {
        this.flowVisible = false
        if (isrRefresh) this.reset()
      },
      reset() {
        for (let key in this.query) {
          this.query[key] = undefined
        }
        this.search()
      },
      handleSelectionChange(val) {
        const res = val.map(item => item.id)
        this.multipleSelection = res
      },
      handleApprove(item, index) {
        return new Promise((resolve, reject) => {
          const num = 100 / this.multipleSelection.length
          approveAssoSupplyInfo(item.id, item).then((res) => {
            this.progressNumApprove += num
            if (res.code === 200) {
              this.successesNumApprove++
            } else {
              this.informationApprove.push(
                '供需信息' + item + ':' + res.msg
              )
              this.failuresNumApprove++
            }
            resolve()
          })
        })
      },
      handleBatchApprove() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: 'error',
            message: '请选择一条数据',
            duration: 1500,
          })
          return
        }
        this.successesNumApprove = 0
        this.failuresNumApprove = 0
        this.progressNumApprove = 0
        this.informationApprove = []
        this.$confirm('是否确认批量审核通过？', '批量审核通过', {
          type: 'warning'
        }).then(() => {
          this.stateProdApprove = true
          this.stateProdUnApprove = true
          this.batchApproveVisible = true
          this.isCardApprove = true
          const asyncFuns = []
          this.multipleSelection.forEach(async (item, index) => {
            asyncFuns.push(this.handleApprove(item, index))
            if ((this.multipleSelection.length - 1) === index) {
              Promise.all(asyncFuns).then(() => {
                this.initData() // 刷新页面
              })
            }
          })
        }).catch(() => {})
      },
      handleUnApprove(item, index) {
        return new Promise((resolve, reject) => {
          const num = 100 / this.multipleSelection.length
          unapproveAssoSupplyInfo(item.id, item).then((res) => {
            this.progressNumUnApprove += num
            if (res.code === 200) {
              this.successesNumUnApprove++
            } else {
              this.informationUnApprove.push(
                '供需信息' + item.materiel_code + ':' + res.msg
              )
              this.failuresNumUnApprove++
            }
            resolve()
          })
        })
      },
      handleBatchUnApprove(command) {
        if (!this.multipleSelection.length) {
          this.$message({
            type: 'error',
            message: '请选择一条数据',
            duration: 1500,
          })
          return
        }
        this.successesNumUnApprove = 0
        this.failuresNumUnApprove = 0
        this.progressNumUnApprove = 0
        this.informationUnApprove = []
        this.$confirm('是否确认批量审核驳回？', '批量审核驳回', {
          type: 'warning'
        }).then(() => {
          this.$prompt('请输入原因', '审核驳回', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            closeOnPressEscape: false,
            inputPlaceholder: '请输入原因，不超过50字'
          }).then(({
            value
          }) => {
            this.stateProdApprove = true
            this.stateProdUnApprove = true
            this.batchUnApproveVisible = true
            this.isCardUnApprove = true
            const asyncFuns = []
            this.multipleSelection.forEach(async (item, index) => {
              item.approvecontent = value
              asyncFuns.push(this.handleUnApprove(item, index))
              if ((this.multipleSelection.length - 1) === index) {
                Promise.all(asyncFuns).then(() => {
                  this.initData() // 刷新页面
                })
              }
            })
          }).catch(() => {});
        }).catch(() => {});
      }
    }
  }
</script>
<style lang="scss" scoped>
  ::v-deep .el-dropdown {
    margin-left: 10px;

    .el-icon--right {
      line-height: 0;
    }
  }
</style>
